//
//  BalanceRechargeTableViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/8/27.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit

class BalanceRechargeTableViewController: BaseTableViewController,UITextFieldDelegate {

    @IBOutlet weak var balance: UILabel!
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var alipayImage: UIImageView!
    @IBOutlet weak var wechatImage: UIImageView!
    
    var payType = 0 //支付方式 0支付宝 1微信
    
    var myBalance = ""
    
    lazy var alertView : AlertContentView = {
        let view = AlertContentView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight))
        UIApplication.shared.keyWindow?.addSubview(view)
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.title = "余额储值"
        self.alipayImage.isHighlighted = true
        self.textField.keyboardType = .decimalPad
        self.balance.text = "￥" + self.myBalance
        Utils.setTextFieldPlaceholderColor(textField: self.textField)
        
        self.textField.delegate = self
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        NotificationCenter.default.addObserver(self, selector: #selector(receivePayResult(notification:)), name: NSNotification.Name(rawValue: "rechargeResult"), object: nil)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "rechargeResult"), object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "rechargeResult"), object: nil)
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField.text?.count == 0 && string == "." {
            return false
        }
        return true
    }
    
    
    @objc func receivePayResult(notification:Notification){
        
        guard let userInfo = notification.object else {
            return
        }
        
        if (userInfo as! postParameters)["isSuccess"] as! Bool == true {
            PKhud.showText(text: "充值成功~")
            let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "CheckstandViewController") as! CheckstandViewController
            ctrl.isRecharge = true
            ctrl.isBalancePay = false
            ctrl.payType = self.payType == 0 ? .alipay : .wechat
            self.navigationController?.pushViewController(ctrl, animated: true)
        }else{
            self.alertView.showRechargeAlert(title: "充值失败", content: (payType == 0 ? "支付宝" : "微信") + "支付失败，本次充值未完成")
        }
    }

    
    // MARK:充值
    @IBAction func rechargeMethod(_ sender: UIButton) {
        guard self.textField.text != "" else {
            PKhud.showText(text: "请填写充值金额~")
            return
        }
        (UIApplication.shared.delegate as! AppDelegate).type = .recharge
        PKhud.show()
        let money = Double.init(self.textField.text!)
        HttpRequest.requestData(.post, URLString: Api.payRecharge.rawValue, parameters: ["money":money!,"payType":self.payType]) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                if self.payType == 0 {
                    // 支付宝
                    AlipaySDK.defaultService().payOrder(result["data"] as! String, fromScheme: "zxsupermarket", callback: { (resultDic) in
                        
                    })
                    
                }else{
                    
                    let isInstall = WXApi.isWXAppInstalled()
                    guard isInstall else {
                        PKhud.showText(text: "您尚未安装微信客户端~")
                        return
                    }
                    // 微信
                    if let dic = result["data"] as? postParameters {
                        let request = PayReq.init()
                        request.partnerId = dic["partnerid"] as! String
                        request.prepayId = dic["prepayid"] as! String
                        request.package = dic["package"] as! String
                        request.nonceStr = dic["noncestr"] as! String
                        request.timeStamp = UInt32(dic["timestamp"] as! String)!
                        request.sign = dic["sign"] as! String
                        WXApi.send(request)
                    }
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    
    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 3
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        if section == 2 {
            return 2
        }else{
            return 1
        }
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 2 {
            if indexPath.row == 0 {
                self.alipayImage.isHighlighted = true
                self.wechatImage.isHighlighted = false
                self.payType = 0
            }else{
                self.alipayImage.isHighlighted = false
                self.wechatImage.isHighlighted = true
                self.payType = 1
            }
        }
    }

    
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section != 0 {
            return 43
        }else{
            return 0.01
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
}
